package controllers.features;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import models.features.LoginMenu;
import views.features.LoginMenuView;
import core.GameLauncher;
import core.GameLauncher.State;
import core.User;

public class LoginMenuController extends KeyAdapter implements ActionListener {

	private LoginMenu model;
	private LoginMenuView view;
	private User currentUser;
	private String userInput;
	private String passInput;
	private String secretQuestion;
	private String secretAnswer;
	private GameLauncher gameLauncher;
	private State state = State.LOGIN;
	private boolean waitForProblem = false;

	public LoginMenuController(LoginMenu model, LoginMenuView view,
			GameLauncher gameLauncher) {
		this.model = model;
		this.view = view;
		this.gameLauncher = gameLauncher;
		view.addActionListenerToGame(this);
		view.addKeyListenerToGame(this);
		if (model.getStatusConnection()) { // true se c'è un problema
			view.signalProblem(true);
			waitForProblem = true;
		}
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (!waitForProblem) {
			Object o = e.getSource();
			// ACCESSO PREMENDO INVIO
			if (o instanceof JTextField) {
				if (state == State.LOGIN)
					login();
			}

			// ACCESSO E ALTRE FUNZIONI DAI JBUTTON
			else {
				// System.out.println(e.getSource());
				JButton input = (JButton) e.getSource();
				switch (input.getName()) {
				case "login":
					login();
					break;
				case "account":
					// System.out.println("Input ricevuto");
					gameLauncher.startTransition(State.REGISTER);
					break;
				case "crea":
					System.out.println("Crea clicked");
					userInput = view.getUserTextField();
					passInput = view.getPassTextField();
					secretQuestion = view.getsecretQuestionTextField();
					secretAnswer = view.getsecretAnswerTextField();
					if (userInput.length() == 0 || passInput.length() == 0
							|| secretQuestion.length() == 0
							|| secretAnswer.length() == 0) {
						// System.out.println("Riempire i campi obbligatori");
						view.showMessage("Riempire i campi obbligatori");
						break;
					}

					try {
						if (model.createUserTuple(new User(userInput,
								passInput, secretQuestion, secretAnswer, 1, 0))) { // tenta
																					// di
																					// inserire
																					// il
																					// nuovo
																					// utente
																					// nel
																					// database.
																					// Se
																					// l'inserimento
							System.out.println("Utente " + userInput
									+ " aggiunto al database");
							view.showMessage("Utente " + userInput
									+ " aggiunto correttamente al database");
						}
						// va a buon fine createUserTuple restituisce true,
						// altrimenti false
						else
							view.showMessage("Utente già presente nel database");
						// System.out.println("Utente già presente nel database");
					} catch (SQLException e1) {
						e1.printStackTrace();
					}
					break;
				case "indietro":
					gameLauncher.startTransition(State.LOGIN);
					break;
				case "password":
					String currentUsername = view.getUserTextField();
					try {
						if (model.verifyUserInput(currentUsername)) {
							String currentSecretQuestion = "";
							System.out.println("Username corrente "
									+ currentUsername);
							currentSecretQuestion = model
									.getSecretQuestion(currentUsername);
							System.out.println("Current Secret Question: "
									+ currentSecretQuestion);
							gameLauncher
									.startTransition(State.RECOVERY_PASSWORD);
						} else
							view.showMessage("Utente inesistente. Inserire un nome utente valido.");
						// System.out.println("Utente non presente");
					} catch (SQLException e1) {
						e1.printStackTrace();
					}
					break;
				case "recovery password":
					userInput = view.getUserTextField();
					secretAnswer = view.getsecretAnswerTextField();
					try {
						String recoveredPass = model.recoveryPassword(
								userInput, secretAnswer);
						gameLauncher.setOldPassword(recoveredPass);
						view.showMessage("Risposta corretta, la password e': "
								+ recoveredPass);
						gameLauncher.startTransition(State.LOGIN);
					} catch (IllegalStateException e1) {
						view.showMessage("Risposta segreta errata");
						System.out.println("Risposta segreta errata");
						view.showSecretAnswerError();
						break;
					} catch (SQLException e1) {
						e1.printStackTrace();
					}
				}
			}
		} else {
			JButton input = (JButton) e.getSource();
			if (input.getText().equalsIgnoreCase(
					"PROBLEMA CONNESSIONE AL DATABASE - CLICK PER RISOLVERLI")) ;
				int i = view.showConfirm();
				File file = null;
				if (i == JOptionPane.YES_OPTION) {
					file = view.getUserFile();
				}
				else if ( i == JOptionPane.NO_OPTION){
					String user = view.askUser();
					if ( user == null || user.length() == 0 )
						return;
					String psw = view.askPassword();
					if ( psw == null || psw.length() == 0)
						return;
					try {
						file = LoginMenu.createAccessFile(user, psw);
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
				try {
					if (model.tryConnection(file)) {
						view.signalProblem(false); // problema risolto e
													// connessione
													// stabilita.
													// Comporta la
													// disabilitazione del
													// pulsante di errore
						waitForProblem = false; // vengono riabilitati tutti
												// gli
												// input
					}
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			}
	}

	public void changeState(State state) {
		this.state = state;
	}

	public void keyReleased(KeyEvent e) {
		Object o = e.getSource();
		if (o instanceof JTextField) {
			JTextField source = (JTextField) o;
			if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE
					&& source.getForeground().equals(Color.RED)) {
				view.removeSecretAnswerError();
			}
		} else if (e.getKeyCode() == KeyEvent.VK_ENTER) {
			System.out.println("ENTER");
			login();
		}
	}

	/**
	 * Effettua il login invocando il metodo creatUserInstance
	 */
	public void login() {
		userInput = view.getUserTextField();
		passInput = view.getPassTextField();

		try {
			currentUser = model.createUserInstance(userInput, passInput);
			System.out.println("USER " + currentUser);
			gameLauncher.startTransition(State.MAIN_MENU);
			System.out.println("Accesso eseguito.\nLogin effettuato da "
					+ userInput.toUpperCase() + " con password "
					+ passInput.toUpperCase());
			gameLauncher.setUser(currentUser);
		} catch (IllegalStateException e3) {
			System.out.println("Utente inesistente");
			view.showMessage("Utente inesistente o password errata. Riprova");
		}
		if (currentUser == null)
			return;
		int level = currentUser.getLevel();
		gameLauncher.prepareLevelBar();

	}

}
